package com.dingshi.security.image;

import java.io.File;
import java.io.FileFilter;
import java.util.Calendar;

import com.dingshi.security.config.CacheConfig;


public class ImageCacheManager {

	/**
	 * 校准定时清理任务时间
	 * 
	 * @param context
	 */
	/*public static void scheduledCleanupTask(Context context) {
		PendingIntent sender = PendingIntent.getService(context, 0, new Intent(context, ImageCacheClearService.class),
				PendingIntent.FLAG_UPDATE_CURRENT);
		// 设定每天10点整开始
		Calendar calendar = Calendar.getInstance();
		long currentTime = calendar.getTimeInMillis();
		calendar.set(Calendar.HOUR_OF_DAY, 10);
		calendar.set(Calendar.MINUTE, 30);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		if (currentTime >= calendar.getTimeInMillis()) {
			calendar.add(Calendar.DAY_OF_MONTH, 1);
		}
		AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarm.cancel(sender);
		alarm.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR * 24, sender);
	}
*/
	/**
	 * 清空缓存文件夹
	 */
	public static void clearAllCache() {
		File file = new File(CacheConfig.getImgDir());
		if (file.exists() && file.isDirectory()) {
			deleteDir(file);
		}
	}

	/**
	 * 清除过期的缓存文件(按一定的策略)
	 */
	public static void clearOverdueCache() {
		if (getCacheSize() > 1024 * 1024 * 10) {
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_MONTH, -10);
			File file = new File(CacheConfig.getImgDir());
			if (file.exists() && file.isDirectory()) {
				deleteFileBeforeTime(file, calendar.getTimeInMillis());
			}
		}
	}
	
	/**
	 * 获取缓存的大小
	 * @return
	 */
	public static int getCacheSize() {
		File file = new File(CacheConfig.getImgDir());
		if (file.exists() && file.isDirectory()) {
			return computeDirSize(file);
		}
		return 0;
	}

	private static void deleteFileBeforeTime(File dir, final long time) {
		File[] listFiles = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				return file.lastModified() > time ? true : false;
			}
		});
		for (File file : listFiles) {
			if (file.exists()) {
				if (file.isFile()) {
					file.delete();
				} else if (file.isDirectory()) {
					deleteFileBeforeTime(file, time);
				}
			}
		}
	}

	private static int computeDirSize(File dir) {
		int size = 0;
		File[] listFiles = dir.listFiles();
		for (File file : listFiles) {
			if (file.exists()) {
				if (file.isFile()) {
					size += (int) file.length();
				} else if (file.isDirectory()) {
					size += computeDirSize(file);
				}
			}
		}
		return size;
	}

	private static void deleteDir(File dir) {
		File[] listFiles = dir.listFiles();
		for (File file : listFiles) {
			if (file.exists()) {
				if (file.isFile()) {
					file.delete();
				} else if (file.isDirectory()) {
					deleteDir(file);
				}
			}
		}
		dir.delete();
	}

}
